const jwt = require("jwt-simple");
const db = require("../core/DBhelper");
const moment = require("moment");
const md5 = require("md5");
const https = require('https');

class UserInfo {
	/**
* @api {post} sys/login 登录
* @apiVersion 1.0.0
* @apiName login
* @apiGroup user模块
* @apiParam {String} user 用户名
* @apiParam {String} pwd  密码
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccess {Object} data 用户信息
* @apiSuccess {String} token 用户信息
* @apiSuccessExample Success-Response:
* 
*  {
			code: 200,
			msg: "登录成功",
			data: { },
			token:"凭证"
	}
*/
	async login(req, res, next) {
		console.log(require("../configs/index").MD5key);
		var oUser = [
			req.body.user,
			md5(md5(req.body.pwd) + require("../configs/index").MD5key),
		]

		//登录的sql语句
		let login_sql = "SELECT `uId`,`username`,`sex`,`avatar`,`nickname`,`status`,`createtime`,`lasttime` "
		login_sql += " FROM `userinfo` WHERE  username=? AND PASSWORD=? AND `status`=1 ;";

		var result_login = await db.exec(login_sql, oUser);
		var isLogin = result_login && result_login.length >= 1;
		//如果登录成功,就去查看当前用户拥有的的菜单和拥有的按钮权限
		if (isLogin) {
			let meun_sql = `
            SELECT * FROM menus WHERE menuid IN(
            SELECT menuid FROM permission WHERE rId IN(
            SELECT rId FROM user_role WHERE uId=
            (SELECT uId FROM userinfo WHERE  username=? AND PASSWORD=? AND STATUS=1) AND STATUS=1
            ) AND STATUS=1 )`;

			let result_menu = await db.exec(meun_sql, oUser)


			//按钮权限
			let btn_sql = `
            SELECT CONCAT(direct,':',btnremark) AS perms FROM (SELECT * FROM menubtn WHERE  rId IN(
                SELECT rId FROM user_role WHERE uId=
                (SELECT uId FROM userinfo WHERE  username=? AND PASSWORD=? AND STATUS=1) AND STATUS=1)) AS a
                LEFT JOIN menus AS b ON a.menuId=b.menuId
                LEFT JOIN btntype AS c ON a.btnId=c.btnId
            `;

			let result_perms = await db.exec(btn_sql, oUser);


			//登录成功后,记录登录的时机
			let update_login_time_sql = "UPDATE `userinfo` SET `lasttime`= ? WHERE uid=? and status=1 ;"
			let update_login_item_params = [
				moment().format("YYYY-MM-DD hh:mm:ss"),
				result_login[0].uId
			]
			await db.exec(update_login_time_sql, update_login_item_params);

			res.json({
				code: 200,
				msg: "登录成功",
				data: {
					userInfo: result_login[0],
					menus: result_menu,
					perms: result_perms.reduce(function (pre, cur) {
						pre.push(cur.perms);
						return pre;
					}, [])
				},

				//tokenAuth 盐
				token: jwt.encode(result_login[0], require("../configs").tokenAuth)
			})


		} else {
			res.json({
				code: -200,
				msg: "登录失败"
			})
		}
	}



	/**
* @api {post} sys/addUser 用户添加
* @apiVersion 1.0.0
* @apiName addUser
* @apiGroup user模块
* @apiParam {String} username 用户名
* @apiParam {String} password  密码
* @apiParam {String} sex  性别(男/女)
* @apiParam {String} avatar  头像(url地址)
* @apiParam {String} nickname  昵称
* @apiParam {String} token  凭证
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccessExample Success-Response:
*  {
		code: 200,
		msg: "登录成功"
	}
*/
	async addUser(req, res, next) {
		//        req[require("../configs").currentUser] 当前的登录人

		let reg_sql = "INSERT INTO userinfo(`username`,`password`,`sex`,`avatar`,`nickname`,`createtime`)VALUES(?,?,?,?,?,?);";
		let req_params = [
			req.body.username,
			md5(md5(req.body.password) + require("../configs").MD5key),
			req.body.sex,
			req.body.avatar,
			req.body.nickname,
			moment().format("YYYY-MM-DD HH:mm:ss"),

		];
		var result_req = await db.exec(reg_sql, req_params);
		var isReg = result_req.affectedRows >= 1;

		res.json({
			code: isReg ? 200 : -200,
			msg: isReg ? "注册成功" : "注册失败"
		})
	}

	/**
* @api {post} sys/update 用户修改
* @apiVersion 1.0.0
* @apiName update
* @apiGroup user模块
* @apiParam {String} password  密码
* @apiParam {String} sex  性别(男/女)
* @apiParam {String} avatar  头像(url地址)
* @apiParam {String} nickname  昵称
* @apiParam {String} status  状态(默认是1,可以不传)
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccessExample Success-Response:
*  {
	code: 200,
	msg: "修改成功"
}
*/
	async update(req, res, next) {

		let update_sql = "UPDATE  userinfo SET `password`=?,`sex`=?,`avatar`=?, `nickname`=?,`status`=? WHERE uId=?;"
		let update_params = [
			md5(md5(req.body.password) + require("./configs").MD5key),
			req.body.sex,
			req.body.avatar,
			req.body.nickname,
			req.body.status == undefined ? 1 : req.body.status, //如果没有传状态,就默认不删除
			req.body.uId
		]

		var result_update = await db.exec(update_sql, update_params);
		var isReg = result_update.affectedRows >= 1;

		res.json({
			code: isReg ? 200 : -200,
			msg: isReg ? "修改成功" : "修改失败"
		})
	}
	/**
* @api {post} sys/delete 用户(软删除)
* @apiVersion 1.0.0
* @apiName delete 
* @apiGroup user模块
* @apiParam {String} uId  用户id
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccessExample Success-Response:
*  {
	code: 200,
	msg: "删除成功"
}
*/
	async delete(req, res, next) {
		let del_sql = "UPDATE  userinfo SET `status`=0 WHERE uId=?";
		let del_params = [
			req.body.uId
		]
		var result_del = await db.exec(del_sql, del_params);
		var isReg = result_del.affectedRows >= 1;

		res.json({
			code: isReg ? 200 : -200,
			msg: isReg ? "删除成功" : "删除失败"
		})
	}

	/**
* @api {get} sys/search 用户模糊搜索
* @apiVersion 1.0.0
* @apiName search 
* @apiGroup user模块
* @apiParam {String} field  (用户名或昵称)
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccessExample Success-Response:
*  { 
				code: 200,
					msg: "查询成功",
					data: []
}
*/
	async search(req, res, next) {
		let search_sql = "SELECT `uId`,`username`,`sex`,`avatar`,`nickname`,`status`,`createtime`,`lasttime` FROM userinfo WHERE `username` LIKE '%?%' OR  `nickname` LIKE '%?%'"
		let search_params = [
			req.query.field
		]
		var results = await db.exec(search_sql, search_params);
		res.json({
			code: 200,
			msg: "查询成功",
			data: results
		})

	}

	/**
* @api {get} sys/getlists 用户分页
* @apiVersion 1.0.0
* @apiName getlists 
* @apiGroup user模块
* @apiParam {Number} pageIndex  (第几页,必须从1开始)
* @apiParam {Number} pageSize  (页大小,默认10条)
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccess {Number} count 数据库的总条数,不是分页的总条
* @apiSuccessExample Success-Response:
*  { 
		code: 200,
			msg: "查询成功",
			data: []
}
*/
	async getlists(req, res, next) {
		let responseString = '';
		https.get('https://m.maoyan.com/ajax/movieOnInfoList', (result) => {
			console.log('statusCode:', result.statusCode);

			result.setEncoding('utf-8');

			result.on('data', function (data) {
				responseString += data;
				console.log('data', data);
			});

			result.on('end', function () {
				//这里接收的参数是字符串形式,需要格式化成json格式使用
				var resultObject = JSON.parse(responseString);
				console.log('resultObject', resultObject);
				res.json({
					code:  200 ,
					msg: "电影列表",
					data: resultObject
			})
			});

		}).on('error', (e) => {
			console.error(e);
		});
	}


}



module.exports = new UserInfo();



// npm run doc
// npm run start